package com.example.zhu95.mytimber;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.example.zhu95.mytimber.activity.BaseActivity;
import com.example.zhu95.mytimber.activity.MainActivity;
import com.example.zhu95.mytimber.entity.SongBean;
import com.example.zhu95.mytimber.entity.SongData;
import com.example.zhu95.mytimber.listener.OnPlayNextSongClickListener;
import com.example.zhu95.mytimber.receiver.StartPlayReceiver;
import com.example.zhu95.mytimber.utils.DBHelper;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.example.zhu95.mytimber.ConstantValue.MusicState_Paused;
import static com.example.zhu95.mytimber.ConstantValue.MusicState_Playing;
import static com.example.zhu95.mytimber.ConstantValue.MusicState_Stop;
import static com.example.zhu95.mytimber.ConstantValue.START_PLAY_RECEIVE;

/**
 * @author zhu95
 */
public class PlayMusicService extends Service {

    private StartPlayReceiver startPlayReceiver;

    private int songid;
    private int targetPosition = -1;
    private String state = MusicState_Paused;
    private MediaPlayer mediaPlayer;
    ScheduledExecutorService executorService;
    static final int notificationId = 1;

    MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            //播放下一首
            new OnPlayNextSongClickListener().onClick(null);
        }
    };

    private PlayMusicBinder playMusicBinder = new PlayMusicBinder();

    public PlayMusicBinder getPlayMusicBinder() {
        return playMusicBinder;
    }

    public int getSongid() {
        return songid;
    }

    public PlayMusicService() {
        songid = BaseActivity.songid;
    }

    public int getTargetPosition() {
        return targetPosition;
    }

    public class PlayMusicBinder extends Binder {
        /**
         * @param songid  需要播放的歌曲
         * @param songids 当前播放的队列歌曲id
         */
        public void playMusic(int songid, String songids) {
            int result = validateSongid(songid);
/*            if (result < 0) {
                return;
            }*/
            if (result == 0) {
                setTargetPosition(mediaPlayer);
                return;
            }
            if (result > 0) {
                boolean b = setMediaPlayer(result);
                if (!b) {
                    return;
                }
                songid = PlayMusicService.this.songid;
                state = MusicState_Playing;
                MyApplication.sendMusicStateBroadcast(songid, state, mediaPlayer.getCurrentPosition(), false);
                startNotification(NotificationCompat.PRIORITY_HIGH);
                //  if (needRecord) {
                DBHelper.addPlayMusicRecord(songid, songids);
                //  }
            }
        }

        public void pauseMusic() {
            state = MusicState_Paused;
            cancelNotification();
            startNotification(NotificationCompat.PRIORITY_MIN);
            MyApplication.sendMusicStateBroadcast(songid, state, mediaPlayer.getCurrentPosition(), false);
            DBHelper.recordCurrentPotision(mediaPlayer.getCurrentPosition());
            mediaPlayer.pause();
        }

        public void stopMusic() {
            state = MusicState_Stop;
            cancelNotification();
            mediaPlayer.reset();
        }

        public void setCurrentPosition(int targetPos) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.seekTo(targetPos);
            } else {
                targetPosition = targetPos;
            }
        }
    }

    /**
     * @param songid 要求播放的歌曲id
     * @return 0 : 需要播放的就是当前播放的，无需处理，
     * 负数:表示错误，
     * 1 : 播放另一首歌
     * 2 : 播放MediaPlayer已有歌曲
     * 3 : 播放新的歌
     */
    private int validateSongid(int songid) {
        if (mediaPlayer == null && songid != -1) {
            this.songid = songid;
            return 3;
        }
        //正在播放,且需要播放的也是同一首歌
        if (this.songid == songid && mediaPlayer.isPlaying()) {
            return 0;
        }
        //要求播放的歌曲id正确且当前播放的歌曲不是要求播放的歌曲，-->那么设置当前播放的歌曲为要求播放的歌曲
        if (this.songid != songid) {
            if (this.songid == -1) {
                this.songid = songid;
                return 3;
            }
            this.songid = songid;
            return 1;
        }
        //要求播放的歌曲未知但当前有一个歌曲id  或者  当前id为要播放的id但是未播放-->那么直接播放当前歌曲
        boolean condition1 = (songid == -1 && this.songid != -1);
        boolean condition2 = (this.songid == songid && !mediaPlayer.isPlaying());
        if (condition1 || condition2) {
            return 2;
        }
        //要求播放的歌曲id为-1且表示当前无歌曲，-->那么设置当前歌曲id为库中第一首歌
        if (songid == -1 && this.songid == -1) {
            try {
                songid = SongData.songs.get(0).getId();
            } catch (Exception e) {
                e.printStackTrace();
                return -1;
            }
            this.songid = songid;
            return 3;
        }
        return -1;
    }

    /**
     * @param condition 1 : 播放另一首歌
     *                  2 : 播放当年前程序记录的已有歌曲
     *                  3 : 播放新的歌
     */
    private boolean setMediaPlayer(int condition) {
        SongBean song = SongData.findSongByID(songid);
        if (song == null) {
            return false;
        }
        try {
            if (condition == 3) {
                if (mediaPlayer == null) {
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setOnCompletionListener(completionListener);
                }
                mediaPlayer.setDataSource(song.getPath());
                mediaPlayer.prepareAsync();
            } else if (condition == 1) {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(song.getPath());
                mediaPlayer.prepareAsync();
            } else if (condition == 2) {
                if (mediaPlayer != null) {
                    //continue to play music
                    setTargetPosition(mediaPlayer);
                    mediaPlayer.start();
                }
                if (mediaPlayer == null) {
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setOnCompletionListener(completionListener);
                    mediaPlayer.setDataSource(song.getPath());
                    mediaPlayer.prepareAsync();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (!mp.isPlaying()) {
                    setTargetPosition(mp);
                    mp.start();
                }
                if (executorService == null) {
                    executorService = Executors.newSingleThreadScheduledExecutor();//newScheduledThreadPool(1);
                    executorService.scheduleAtFixedRate(new Runnable() {
                        @Override
                        public void run() {
                            if (TextUtils.equals(state, MusicState_Playing)) {
                                MyApplication.sendMusicStateBroadcast(PlayMusicService.this.getSongid(),
                                        state, mediaPlayer.getCurrentPosition(), true);
                            }
                        }
                    }, 0, 500, TimeUnit.MILLISECONDS);
                }
            }
        };

        mediaPlayer.setOnPreparedListener(onPreparedListener);
        return true;
    }

    private void setTargetPosition(MediaPlayer mp) {
        if (targetPosition != -1) {
            mp.seekTo(targetPosition);
            //不需要使用时置为1
            targetPosition = -1;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return playMusicBinder;
    }

    private void startNotification(int priority) {
        SongBean song = SongData.findSongByID(songid);
        Intent playMusicIntent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, playMusicIntent, 0);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle(song.getTitle())
                .setContentText(song.getArtist())
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(priority)
                .setContentIntent(pi)
                .build();
        if (priority > NotificationCompat.PRIORITY_DEFAULT) {
            startForeground(notificationId, notification);
        } else {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.notify(notificationId, notification);
        }
    }

    private void cancelNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        stopForeground(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //注册广播接收器
        if (startPlayReceiver == null) {
            startPlayReceiver = new StartPlayReceiver(this);
            IntentFilter intentFilter = new IntentFilter(START_PLAY_RECEIVE);
            MyApplication.getLocalBroadcastManager().registerReceiver(startPlayReceiver, intentFilter);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        //解除广播接收器
        if (startPlayReceiver != null) {
            MyApplication.getLocalBroadcastManager().unregisterReceiver(startPlayReceiver);
        }
        startPlayReceiver = null;
    }

}
